const httpbinInstance = require('../utils/request');
const constant = require('./constant');
const storage = require('../utils/storage');
// 获取code换存token
export const login = () => {
  return new Promise((resolve,reject) => {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if(res.code && res.code != ''){
          getToken(res.code).then(res => {
            if(res.code == 0){
              resolve(res);
            }
          })
        }
      },
      fail:res => {

      }
    })
  })
  
}
// 获取token
export const getToken = (code) => {
  return new Promise((resolve,reject) => {
    wx.request({
      url: constant.BASEURL + '/login/wechat',
      method:'post',
      data: {code},
      header: {'Authorization':'Bearer ','Deviceid':'loveqing'},
      success: res => {  // code:50005 token过期
        // 存token
        storage.setJwtToken(res.data.data.data.token)
        resolve(res.data)
      },
      fail: err => {
        reject(err)
      },
      complete:()=>{
        // wx.hideLoading()
      }
    })
})
}
// 验证token
export const checkToken = () => {
  let tokenStr = wx.getStorageSync(storage.LOCAL_JWT_KEY);
  return new Promise((resolve,reject) => {
      wx.request({
        url: 'https://api.changlejiuhang.com/token/index',
        method:'post',
        data: {},
        header: {'Authorization':'Bearer '+ tokenStr,'Deviceid':'loveqing'},
        success: res => {
          //  if(res.data.code == 0){
          //   res.data.token = tokenStr;
          //   resolve(res.data)
          //  }
          if(res.data.code == 0){
            res.data.token = tokenStr;
           }
           resolve(res.data)
        }
      })
  })
}
// 获取用户地址
export const getAddress = () => {
 return new Promise((resolve,reject) => {
  httpbinInstance.request({
    url:'/address/list',
    method:'post',
    data:{}
    }).then(res => {
      resolve(res)
    })
 }) 
}
// 新增用户地址
export const addAddress = (formData) => {
  return new Promise((resolve,reject) => {
   httpbinInstance.request({
     url:'/address/add',
     method:'post',
     data:formData
     }).then(res => {
       resolve(res)
     })
  }) 
 }
// 编辑用户地址
export const editAddress = (formData) => {
  return new Promise((resolve,reject) => {
   httpbinInstance.request({
     url:'/address/update',
     method:'post',
     data:formData
     }).then(res => {
       resolve(res)
     })
  }) 
 }
// 删除用户地址
export const deleteAddress = (address_id) => {
  return new Promise((resolve,reject) => {
   httpbinInstance.request({
     url:'/address/delete',
     method:'post',
     data:{
      address_id
     }
     }).then(res => {
       resolve(res)
     })
  }) 
 }
// 获取微信用户信息
export const getUserInfo = () => {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              storage.setAvatarUrl(res.userInfo.avatarUrl);
              storage.setNickname(res.userInfo.nickName);
              // this.setData({
              //   userInfo: res.userInfo
              // })
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              // if (this.userInfoReadyCallback) {
              //   this.userInfoReadyCallback(res)
              // }
            }
          })
        }else{
          wx.authorize({
            scope: 'scope.userInfo',
            success () {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
            }
          })
        }
      }
    })
}

// 同步用户信息
export const syncUserInfo = (nickName,avatarUrl,country,province,city) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url:'/user/wechatuserinfo',
      method:'post',
      data:{
        nick_name: nickName,
        avatar_url: avatarUrl,
        country,
        province,
        city
      }
      }).then(res => {
        resolve(res)
      })
   })
}

// 账号密码登录
export const passwordLogin = (username,password) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url:'/login/system',
      method:'post',
      data:{
        identifier: username,
        credential: password
      }
      }).then(res => {
        resolve(res)
      })
   })
}

// 获取用户信息
export const getUserDetail = () => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url:'/user/show',
      method:'post',
      data:{}
      }).then(res => {
        resolve(res)
      })
   })
}

// 获取手机验证码
export const getPhoneCode = (phone) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url:'/user/postmobile',
      method:'post',
      data:{
        mobile: phone
      }
      }).then(res => {
        resolve(res)
      })
   })
}

// 验证手机验证码
export const checkPhoneCode = (phone,code) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url:'/user/checkmobile',
      method:'post',
      data:{
        mobile: phone,
        code
      }
      }).then(res => {
        resolve(res)
      })
   })
}

// 手机登录
export const phoneLogin = (phone,code) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url:'/login/mobile',
      method:'post',
      data:{
        mobile: phone,
        code
      }
    }).then(res => {
        resolve(res)
      })
   })
}

// 搜索商品列表
export const search = (pagination,screen) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/goods/lists',
      method: 'post',
      data:{
        ...pagination,
        ...screen
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 商品详情
export const getGoodsDetail = (goods_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/goods/show',
      method: 'post',
      data:{
        goods_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 商品评价
export const getGoodsEvaluate = (screen,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/comment/list',
      method: 'post',
      data:{
        ...screen,
        pageNum:pagination.pageNum,
        pageSize:pagination.pageSize
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 商品评价-详情
export const showGoodsEvaluate = (comment_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/comment/list',
      method: 'post',
      data:{
        comment_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 购物车列表
export const carList = (cart_ids) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/cart/me',
      method: 'post',
      data:{
        cart_ids
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 加入购物车
export const addToCart = (queryform) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/cart/add',
      method: 'post',
      data:{
        goods:queryform
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 购物车数量
export const editCarNum = (cart_id,goods_num) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/cart/updatenum',
      method: 'post',
      data:{
        cart_id,
        goods_num
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 移除购物车
export const deleteToCart = (cart_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/cart/delete',
      method: 'post',
      data:{
        cart_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 商品圈
// 购物车列表
export const goodsCircleList = () => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/friend/lists',
      method: 'post',
      data:{}
    }).then(res => {
      resolve(res);
    })
  })
}
// 创建订单
export const creatOrder = (old_goods,userInfo) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/create',
      method: 'post',
      data:{
        old_goods,
        consignee: userInfo.consignee,
        mobile : userInfo.mobile,
        region: userInfo.region,
        address: userInfo.address,
        zipcode: userInfo.zipcode,
        tel: userInfo.tel,
        buyer_remark : userInfo.buyer_remark,
        source: userInfo.source
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 列表订单
export const getOrderList = (trade_status,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/lists',
      method: 'post',
      data:{
        trade_status,
        pageNum:pagination.pageNum,
        pageSize:pagination.pageSize
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 列表订单(待支付或待配送订单)
export const getOrderListIsOrNotPay = (trade_status,pay_status,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/lists',
      method: 'post',
      data:{
        trade_status,
        pay_status,
        pageNum:pagination.pageNum,
        pageSize:pagination.pageSize
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 退货订单（满足退货条件）
export const getAfterSalesOrderList = (pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/lists',
      method: 'post',
      data:{
        pay_status:1,
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 退货订单商品(根据订单查商品)
export const getAfterSalesGoodsList = (order_no,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/lists',
      method: 'post',
      data:{
        order_no,
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 退货订单详情
export const getAfterSalesOrderDetail = (order_no,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/show',
      method: 'post',
      data:{
        order_no,
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 处理中的售后处理中的订单
export const getInProcessList = (trade_status,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/refund/lists',
      method: 'post',
      data:{
        trade_status,
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 申请退货
export const applyRefound = (requestData) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/refund/create',
      method: 'post',
      data:{
        ...requestData
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 获取支付参数和秘钥
export const getPayOptions = (code,order_no) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/pay/wechat',
      method: 'post',
      data:{
        code,
        order_no
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 取消微信支付
export const cancelPay = (order_no) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/cancelwxpay',
      method: 'post',
      data:{
        order_no
      }
    }).then(res => {
      resolve(res);
    })
  })
}
export const cancelOrder = (order_no) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/cancel',
      method: 'post',
      data:{
        order_no
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 删除订单[批量]
export const deleteOrder = (order_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/delete',
      method: 'post',
      data:{
        order_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 确认收货[单个]
export const confirmOrder = (order_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/receive',
      method: 'post',
      data:{
        order_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 商品圈商品
export const friendGoods = (frend_id,pagination,screen) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/friend/goods',
      method: 'post',
      data:{
        frend_id,
        pageNum:pagination.pageNum,
        pageSize:pagination.pageSize,
        orderK: screen.orderK,
        orderV: screen.orderV
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 首页猜你喜欢
export const getGuessListData = (screen,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/goods/lists',
      method: 'post',
      data:{
        ...screen,
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 首页猜你喜欢(随机)
export const getGuessListRandData = (screen,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/goods/rand',
      method: 'post',
      data:{
        ...screen,
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 新闻列表
export const getNewsListData = (pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/news/lists',
      method: 'post',
      data:{
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 新闻详情
export const getNewsDetail = (article_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/news/show',
      method: 'post',
      data:{
        article_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 获取access_token
export const getAccessToken = () => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/login/getAccessToken',
      method: 'post',
      data:{
        grant_type: 'client_credential'
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 获取二维码
export const getCode = (page,scene,width,is_hyaline) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/login/getwxacodeunlimit',
      method: 'post',
      data:{
        page,
        scene,
        width,
        is_hyaline
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 获取一级分类列表
export const getFatherTypeList = () => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/category/first',
      method: 'post',
      data:{}
    }).then(res => {
      resolve(res);
    })
  })
}

// 获取品牌列表(goods_category_id:数组)
export const getBrandList = (goods_category_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/category/brand',
      method: 'post',
      data:{
        goods_category_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 品牌树（无根，且为状态正常，含子级）
export const getBrandListTree = () => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/brand/usertree',
      method: 'post',
    }).then(res => {
      resolve(res);
    })
  })
}
// 获取筛选列表(goods_category_id:数组)
export const getScreenList = (goods_category_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/category/screen',
      method: 'post',
      data:{
        goods_category_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 评价列表
export const getOrderCommentList = (is_comment,pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/trade/lists',
      method: 'post',
      data:{
        trade_status: 2,
        is_comment,
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 提交评价
export const addComment = (queryform) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/comment/add',
      method: 'post',
      data:{
        ...queryform
      }
    }).then(res => {
      resolve(res);
    })
  })
}

// 热搜词
export const getHotSearchList = () => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/hotkeyword/lists',
      method: 'post',
      data:{}
    }).then(res => {
      resolve(res);
    })
  })
}

// 检查是否绑定手机
export const checkPhoneNumber = () => {
  return new Promise((resolve,reject) => {
    let phoneNumberStatus =  wx.getStorageSync(storage.PHONENUMBERSTATUS);
    if(phoneNumberStatus === ""){
      getUserDetail().then(res => {
        if(res.code == 0){
          if(res.data.data.phone_no == ""){
            storage.setPhoneNumberStatus(0);
            resolve(false);
          }else{
            storage.setPhoneNumberStatus(1);
            resolve(true);
          }
        }
      })
    }else{
      if(phoneNumberStatus == 1){
        resolve(true);
      }else{
        resolve(false);
      }
    }
  })
  
  // return new Promise((resolve,reject) => {
  //   httpbinInstance.request({
  //     url: '/user/wechatuserphone',
  //     method: 'post',
  //     data:{
  //       encryptedData,
  //       iv
  //     }
  //   }).then(res => {
  //     resolve(res);
  //   })
  // })
}
// 绑定手机
export const setPhoneNumber = (encryptedData,iv) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/user/wechatuserphone',
      method: 'post',
      data:{
        encryptedData,
        iv
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 商品收藏
export const addCollection = (goods_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/collect/add',
      method: 'post',
      data:{
        goods_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 取消收藏
export const cancelCollection = (goods_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/collect/cancel',
      method: 'post',
      data:{
        goods_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 商品收藏列表
export const getCollectionList = (pagination) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/collect/lists',
      method: 'post',
      data:{
        ...pagination
      }
    }).then(res => {
      resolve(res);
    })
  })
}
// 移除收藏列表
export const deleteCollectionList = (collect_id) => {
  return new Promise((resolve,reject) => {
    httpbinInstance.request({
      url: '/collect/delete',
      method: 'post',
      data:{
        collect_id
      }
    }).then(res => {
      resolve(res);
    })
  })
}